'use strict';

const uidObj = require('uni-id');

const createConfig = require('uni-config-center');

const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const {
	Controller
} = require('uni-cloud-router');

module.exports = class MemberController extends Controller {
	// 提现
	async cashout() {
		let response = {
			code: 1,
			datas: ''
		};

		/* response.msg = '当前提现功能未开启，请自行注释或删除后使用';
		return response; */

		let start = Date.now();

		// 请求参数
		const req = this.ctx.data;
		let {
			id,
			type,
			content
		} = req;

		const cashoutRes = await this.db.collection('wmzmall-member-cashout')
			.doc(id)
			.get();

		if (!(cashoutRes.data && cashoutRes.data.length == 1)) {
			response.msg = `当前提现数据不存在`;
			return response;
		}

		const cashoutData = cashoutRes.data[0];

		const memberRes = await this.db.collection('wmzmall-member').doc(cashoutData.uid).get();
		const memberData = memberRes.data[0];

		if (type == '已提现') {
			const walletParameterRes = await this.db.collection('wmzmall-wallet-parameter').limit(1).get();
			const walletParameterData = walletParameterRes.data[0];

			let trade_no = '';
			let payment_no = '';

			if (cashoutData.cashout_way == '微信零钱') {
				trade_no = Date.now() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0');

				// 微信企业付款到零钱 agent url
				const url = uidConfig.config('agent.wxpay-transfers');

				// 申请提现金额（单位元）
				const cashout_amount = cashoutData.cashout_amount / 100;
				// 手续费 = 提现金额 * 提现手续费比例 / 100
				const service_charge = cashout_amount * (walletParameterData.service_charge / 100);
				// 提现金额 = 提现金额 - 手续费
				const amount = (cashout_amount - service_charge).toFixed(2);

				const result = await this.curl(url, {
					nestedQuerystring: true,
					method: 'post',
					headers: {
						'Content-Type': 'application/json'
					},
					dataType: 'json',
					data: {
						trade_no: trade_no,
						openid: memberData.member_openid,
						truename: memberData.member_truename,
						check_name: walletParameterData
							.check_name, // 是否校验实名合法性 NO_CHECK、FORCE_CHECK、OPTION_CHECK
						amount: amount * 100, // 提现金额（单位分）
						desc: content
					}
				});

				const wxpayRes = result.data;

				if (wxpayRes.code !== 200) {
					response.msg = wxpayRes.msg;
					return response;
				}

				// 微信支付编号
				payment_no = wxpayRes.datas.payment_no;
			}

			// 提现成功
			// 累计提现金额 profit_amount += 提现金额
			// 待审提现 unprofit_amount -= 提现金额
			await this.db.collection('wmzmall-member').doc(cashoutData.uid).update({
				profit_amount: this.db.command.inc(cashoutData.cashout_amount),
				unprofit_amount: this.db.command.inc(-cashoutData.cashout_amount),
				version: this.db.command.inc(1)
			});

			await this.db.collection('wmzmall-member-cashout').doc(id).update({
				trade_no: trade_no,
				payment_no: payment_no,
				cashout_desc: content,
				state: type,
				last_modify_time: Date.now(),
				last_modify_uid: this.ctx.auth.uid,
				last_modify_uname: this.ctx.auth.userInfo.username
			});
		} else if (type == '提现失败') {
			// 提现失败
			// 零钱余额 member_amount += 提现金额
			// 待审提现 unprofit_amount -= 提现金额
			await this.db.collection('wmzmall-member').doc(cashoutData.uid).update({
				member_amount: this.db.command.inc(cashoutData.cashout_amount),
				unprofit_amount: this.db.command.inc(-cashoutData.cashout_amount),
				version: this.db.command.inc(1)
			});

			await this.db.collection('wmzmall-member-cashout').doc(id).update({
				cashout_fail: content,
				state: type,
				last_modify_time: Date.now(),
				last_modify_uid: this.ctx.auth.uid,
				last_modify_uname: this.ctx.auth.userInfo.username
			});
		}

		response.datas = '操作成功';

		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 查询提现进度
	async getCashoutProgress() {
		let response = {
			code: 1,
			datas: ''
		};
		
		let start = Date.now();
		
		// 请求参数
		const req = this.ctx.data;
		let {
			id
		} = req;
		
		const cashoutRes = await this.db.collection('wmzmall-member-cashout')
			.doc(id)
			.get();
		
		if (!(cashoutRes.data && cashoutRes.data.length == 1)) {
			response.msg = `当前提现数据不存在`;
			return response;
		}
		
		const cashoutData = cashoutRes.data[0];
		
		// 查询微信企业付款到零钱 agent url
		const url = uidConfig.config('agent.wxpay-transfersQuery');
		
		const result = await this.curl(url, {
			nestedQuerystring: true,
			method: 'post',
			headers: {
				'Content-Type': 'application/json'
			},
			dataType: 'json',
			data: {
				trade_no: cashoutData.trade_no
			}
		});
		
		response.datas = result.data.datas;
		
		let end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
}
